package com.shopping_back.controller;

import com.shopping_back.common.Result;
import com.shopping_back.pojo.entity.UserProfile;
import com.shopping_back.service.IUserProfileService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关API控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final IUserProfileService userProfileService;
    private final JwtUtils jwtUtils;

    /**
     * 获取用户余额信息
     * GET /api/user/balance
     */
    @GetMapping("/balance")
    public Result getUserBalance(HttpServletRequest request) {
        try {
            // 从Token获取用户ID
            Long userId = jwtUtils.getCurrentUserId(request);
            if (userId == null) {
                // 临时使用固定用户ID进行测试
                userId = 3L;
            }

            // 查询用户资料
            UserProfile profile = userProfileService.getByUserId(userId);
            if (profile == null) {
                return Result.error("用户信息不存在");
            }

            // 返回余额信息
            Map<String, Object> data = new HashMap<>();
            data.put("balance", profile.getWallet() != null ? profile.getWallet() : 0);
            data.put("userId", userId);

            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取余额信息失败: " + e.getMessage());
        }
    }
}